﻿using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml;
using ZzgkChatRoom.Component;
using ZzgkChatRoom.Models;

namespace ZzgkChatRoom.ViewModels
{
    public partial class ChatWindowViewModel : ObservableObject
    {
        [ObservableProperty]
        string _roomName;
        [ObservableProperty]
        double _pageWidth;
        [ObservableProperty]
        ObservableCollection<ChatMsg> _chatMsgCollection = new ObservableCollection<ChatMsg>();
        [ObservableProperty]
        ObservableCollection<GroupInfo> _groupInfoCollection = new ObservableCollection<GroupInfo>();
        [ObservableProperty]
        List<EmojiEntity> _emojiList =new List<EmojiEntity>();

        List<string> imgList = new List<string>();

        private Dictionary<string, string> emojiCode = new Dictionary<string, string>();

        public ChatWindowViewModel(double windowW) { 
            PageWidth = windowW * 0.75;
            BuildGroup();
            AnayXml();

        }

        public void BuildGroup() {
            for (int i = 0;i<1;i++) {
                GroupInfo groupInfo = new GroupInfo();
                groupInfo.Id = i;
                groupInfo.Header = "http://images.nowcoder.com/head/588t.png";
                groupInfo.Name = "装备事业部"+i;
                groupInfo.Time = "9:50";
                // groupInfo.MessageNum = 124;
                groupInfo.Message = "软件组表现不错，每人8万奖金";
                GroupInfoCollection.Add(groupInfo);
            }
        }

        public void OthersMsgTest(String username,String msg) {
            ChatMsg chatMsg = new ChatMsg();
            chatMsg.Id = 1;
            chatMsg.Username = username;
            chatMsg.Message = msg;
            chatMsg.MessageFD = BuildFlowDocument(msg); 
           //  chatMsg.MessageFDW = chatMsg.MessageFD.PageWidth;
            chatMsg.MessageBackground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#E8E8E9"));
            chatMsg.MessageAlignment = System.Windows.HorizontalAlignment.Left;
            chatMsg.MessageTime = "2024年1月5日 14:28";
            ChatMsgCollection.Add(chatMsg);
        }

       

        public string GetSendMessage(FlowDocument fld) {
            if (fld == null) { 
                return string.Empty;
            }
            string resutStr = string.Empty;
            foreach (var root in fld.Blocks) {
                foreach (var item in ((Paragraph)root).Inlines) {
                    //如果是Emoji则进行转换
                    if (item is InlineUIContainer) {
                        Image image = (System.Windows.Controls.Image)((InlineUIContainer)item).Child;

                        // imgList.Add(image.Source.ToString());
                        resutStr += "["+ image.Tag+"]";
                    }
                    //如果是文本，则直接赋值
                    if (item is Run) {
                        resutStr += ((Run)item).Text;
                    }
                }
            }
            return resutStr;
        }

        public void SendMsg(FlowDocument flowDocument) {
            string s = GetSendMessage(flowDocument);
            ChatMsg chatMsg = new ChatMsg();
            chatMsg.Id = 1;
            chatMsg.Username = "我";
            FlowDocument document = new FlowDocument();
           // document.PageWidth = 800;
            StrToFlDoc(s, document, new Paragraph());
            chatMsg.Header = "http://images.nowcoder.com/head/518t.png";
            chatMsg.MessageFD = document; 
          //  chatMsg.MessageFD = BuildFlowDocument(s);
            chatMsg.MessageDirection = FlowDirection.RightToLeft;
            chatMsg.MessageFDW = chatMsg.MessageFD.PageWidth;
            chatMsg.MessageBackground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#C9E7FF"));
            chatMsg.MessageAlignment = System.Windows.HorizontalAlignment.Right;
            chatMsg.MessageTime = "2024年1月5日 14:28";
            ChatMsgCollection.Add(chatMsg);
        }

        //private string FlDocToStr(FlowDocument document) {

        //}

        /// <summary>
        /// 将字符串转换成FlowDocument
        /// </summary>
        /// <param name="str">原始字符串</param>
        /// <param name="fld">要被赋值的Flowdocument</param>
        /// <param name="par">要添加到Flowdocument里的Paragraph</param>
        private void StrToFlDoc(string str, FlowDocument fld, Paragraph par)
        {
            //当递归结束以后，也就是长度为0的时候，就跳出
            if (str.Length <= 0)
            {
                fld.Blocks.Add(par);
                return;
            }
            //如果字符串里不存在[时，则直接添加内容
            if (!str.Contains('['))
            {
                par.Inlines.Add(new Run(str));
                str = str.Remove(0, str.Length);
                StrToFlDoc(str, fld, par);
            }
            else
            {
                //设置字符串长度
                int strLength = str.Length;
                //首先判断第一位是不是[，如果是，则证明是表情，用正则获取表情，然后将字符串长度进行移除，递归
                if (str[0].Equals('['))
                {
                    string x = GetEmojiNameByRegex(str);
                    if (emojiCode.ContainsKey(x)) {
                        BitmapImage bitImage = new BitmapImage();
                        bitImage.BeginInit();
                        bitImage.UriSource = new Uri(getEmojiUrl(emojiCode[x]), UriKind.RelativeOrAbsolute);
                        bitImage.EndInit();
                        Image image = new Image();
                        image.Source = bitImage;
                        image.Width = 20;
                        image.Height = 20;
                        par.Inlines.Add(image);
                        str = str.Remove(0, x.Length);
                        StrToFlDoc(str, fld, par);
                    }
                    else {
                        par.Inlines.Add(new Run(x));
                        str = str.Remove(0, x.Length);
                        StrToFlDoc(str, fld, par);
                    }
                    // par.Inlines.Add(new InlineUIContainer(new System.Windows.Controls.Image { Width = 20, Height = 20, Source =  }));
                    //par.Inlines.Add(new InlineUIContainer(new System.Windows.Controls.Image { Width = 20, Height = 20, Source = emojiCode[] }));
                    //str = str.Remove(0, GetEmojiNameByRegex(str).Length);
                    //StrToFlDoc(str, fld, par);
                }
                else
                {//如果第一位不是[的话，则是字符串，直接添加进去
                    par.Inlines.Add(new Run(GetTextByRegex(str)));
                    str = str.Remove(0, GetTextByRegex(str).Length);
                    StrToFlDoc(str, fld, par);
                }
            }
        }

        /// <summary>
        /// 根据消息信息创建FlowDocument
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public FlowDocument BuildFlowDocument(string msg) {
            FlowDocument document = new FlowDocument();
          //  double x  = GetTextWidth(msg, 15.3, "Microsoft YaHei");
            var p = new Paragraph();
            p.Inlines.Add(msg);
            document.Blocks.Add(p);
            //imgList.Clear();
            //if (x + 20 > 800)
            //{
            //    document.PageWidth = 800;
            //}else
            //    document.PageWidth = x + 20;
            return document;
        }


        /// <summary>
        /// 获取Emoji的名字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private string GetEmojiNameByRegex(string str) {
            string name = Regex.Match(str, "(?<=\\[).*?(?=\\])").Value;
            return "["+name+"]";
        }

        /// <summary>
        /// 获取文本信息
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private string GetTextByRegex(string str)
        {
            string text = Regex.Match(str, "^.*?(?=\\[)").Value;
            return text;
        }

        /// <summary>
        /// 获取字符中指标签的值
        /// </summary>
        /// <param name="str"></param>
        /// <param name="title"></param>
        /// <returns></returns>
        public string GetTitleContent(string str,string title) {
            string tmpStr = string.Format("<{0}[^>]*?>(?<Text>[^<]*)</{1}>", title, title); //获取<title>之间内容
            Match TitleMatch = Regex.Match(str, tmpStr, RegexOptions.IgnoreCase);
            string result = TitleMatch.Groups["Text"].Value;
            return result;
        }

        /// <summary>
        /// 获取字符串的宽度
        /// </summary>
        /// <param name="text">消息</param>
        /// <param name="fontsize"></param>
        /// <param name="fontFamily"></param>
        /// <returns></returns>
        public double GetTextWidth(string text,double fontsize,string fontFamily)
        {
            FormattedText formattedText = new FormattedText(
                text,
                System.Globalization.CultureInfo.InvariantCulture,
                FlowDirection.LeftToRight,
                new Typeface(fontFamily.ToString()),
                fontsize,
                Brushes.Black
            );

            return formattedText.WidthIncludingTrailingWhitespace;
        }

        /// <summary>
        /// 解析xml
        /// </summary>
        public void AnayXml()
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(Path.Combine(Environment.CurrentDirectory, @"Resource/Emoji/list.xml"));
            XmlNode root = xmlDoc.SelectSingleNode("array");
            XmlNodeList nodeList = root.ChildNodes;
            foreach (XmlNode xn in nodeList)
            {
                XmlElement xe = (XmlElement)xn;
                XmlNodeList subList = xe.ChildNodes;
                EmojiEntity entity = new EmojiEntity();
                foreach (XmlNode xmlNode in subList)
                {
                    if (xmlNode.Name == "key")
                    {
                        entity.Key = xmlNode.InnerText;
                    }
                    if (xmlNode.Name == "array")
                    {
                        XmlElement lastXe = (XmlElement)xmlNode;
                        foreach (XmlNode lastNode in lastXe)
                        {
                            if (lastNode.Name == "e")
                            {
                                
                                entity.EmojiCode.Add(lastNode.InnerText, GetEmojiPath(entity.Key,lastNode.InnerText));
                                emojiCode.Add("["+lastNode.InnerText+"]", GetEmojiPath(entity.Key, lastNode.InnerText));
                            }
                        }
                    }
                }
                EmojiList.Add(entity);


            }

        }

        public string getEmojiUrl(string path) {
            string ExePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            path = path.Substring(path.IndexOf("/") + 1);
            return ExePath + path;
        }

        /// <summary>
        /// 返回Emoji路径
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private string GetEmojiPath(string key,string name)
        {
            return "../Resource/Emoji/" + key+"/" + name + ".png";
        }

        /// <summary>
        /// 进入聊天室。
        /// </summary>
        /// <param name="info"></param>
        public void IntoCharRoom(GroupInfo info) {
            RoomName = info.Name;
            ChatMsgCollection.Clear();
            ChatMsgCollection = new ObservableCollection<ChatMsg>();
        }

    
    }

  
}
